package worklog.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import worklog.db.*;
import worklog.dto.ProjectDTO;
import worklog.dto.ResponseDTO;

@WebServlet("/deleteProject")
public class DeleteProject extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ProjectDB projectDB;
	private ResponseDTO responder = new ResponseDTO();

    public DeleteProject() { super(); }
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		//doGet(request, response); 
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		projectDB = new ProjectDB();
		PrintWriter out = response.getWriter();
		response.setContentType("application/json");
    	out.print(processRequest(request));
    	projectDB.close();
    	out.close();
	}

	private String processRequest(HttpServletRequest request){
		HttpSession session = request.getSession();
		if (session.getAttribute("logged") == null || (Boolean)session.getAttribute("logged") != true) return responder.showAuthError();
		int userId = (Integer) session.getAttribute("userId");

		String id;
		int paramLength = request.getParameterMap().size();
		int projectId, res;
		ProjectDTO oldProject;
        
    	if (paramLength == 0) return responder.showError();
		id = request.getParameter("id");
		if (id == null) return responder.showError("Project ID is empty");
		
		try{ projectId = Integer.parseInt(id); }
		catch(NumberFormatException e){ projectId = -1; }
		
		if (projectId == -1) return responder.showError("Incorrect projet ID");
		oldProject = projectDB.getProject(projectId, userId);
		if (oldProject.getId() <= 0) return responder.showError("Project does not exist");
		
		res = projectDB.deleteProject(projectId);
		if (res != -1) return oldProject.toString();
		return responder.showError("DB error");
	}

}
